package core

import (
	"xrt/constants"
	. "xrt/interfaces"
	"xrt/utils"
	"xrt/utils/file/log"
)

/*
Service通过NameSpace分割命名空间,
从自身一层开始向上递归查找, 找不到则抛出异常
*/

type Service struct {
	Sql       IfSql  //Sql操作接口
	NoSql     NoSql  //NoSql操作接口
	nameSpace string //命名空间
}

func getLastNameSpace(nameSpace string) string {
	//最后到根目录都查询不到就结束
	if nameSpace == "/" {
		return constants.EmptyString
	}
	nameSpace = utils.RSplitN(nameSpace, "/", 2)[0]
	//处理一下根路径
	if nameSpace == constants.EmptyString {
		nameSpace = "/"
	}
	return nameSpace
}

func (se *Service) Do(serviceName string, params ...interface{}) {
	se.Exec(serviceName, params...)
}

func (se *Service) Exec(serviceName string, params ...interface{}) interface{} {
	nameSpace := se.nameSpace
	for len(nameSpace) > 0 {
		if servicesMap, exists := X.servicesMap[nameSpace]; exists {
			if _, exists := servicesMap[serviceName]; exists {
				return servicesMap[serviceName](params...)
			}
		}
		nameSpace = getLastNameSpace(nameSpace)
	}
	log.Errorf("ServiceName [%s] Not Exists.", serviceName)
	return nil
}
